module fp32_to_bf16 (
    input  logic [31:0] fp32_data,
    output logic [15:0] bf16_data
);

    logic        sign;
    logic [ 7:0] exponent;
    logic [22:0] mantissa;
    logic        is_nan;
    logic        is_inf;
    logic        guard_bit;
    logic [14:0] sticky_bits;
    logic        rounding_bit;
    logic        sticky_or;
    logic        round_up;
    logic [15:0] bf16_rounded;

    always_comb begin
        sign         = fp32_data[31];
        exponent     = fp32_data[30:23];
        mantissa     = fp32_data[22:0];

        is_nan       = (exponent == 8'hFF) && (mantissa != 23'h0);
        is_inf       = (exponent == 8'hFF) && (mantissa == 23'h0);

        guard_bit    = fp32_data[15];
        sticky_bits  = fp32_data[14:0];
        rounding_bit = fp32_data[16];
        sticky_or    = |sticky_bits;

        round_up     = guard_bit & (sticky_or || rounding_bit);

        if (round_up) begin
            bf16_rounded = fp32_data[31:16] + 16'h0001;
        end else begin
            bf16_rounded = fp32_data[31:16];
        end

        if (is_nan) begin
            bf16_data = 16'h7FC0;
        end else if (is_inf && !sign) begin
            bf16_data = 16'h7F80;
        end else if (is_inf && sign) begin
            bf16_data = 16'hFF80;
        end else begin
            bf16_data = bf16_rounded;
        end
    end

endmodule
